<!-- 智能退货报表 -->

<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form>
      <a-row :gutter="[8, 10]">
        <a-col :span="7">
          <a-form-item label="" name="time_type" class="smart-margin-bottom0">
            <a-space>
              <a-select ref="select" v-model:value="formData.time_type" placeholder="时间类型" style="width: 120px">
                <a-select-option :value="1">单据日期</a-select-option>
                <a-select-option :value="2">签收时间</a-select-option>
                <a-select-option :value="3">出库时间</a-select-option>
              </a-select>
              <custom-range-picker v-model:value="formData.create_time" />
            </a-space>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="门店名称" class="smart-margin-bottom0">
            <Select name="Store" v-model:value="formData.store_id" :multiple="true" placeholder="门店名称" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="单位类型" name="payment_type" class="smart-margin-bottom0">
            <a-select ref="select" v-model:value="formData.unit_type" placeholder="单位类型">
              <a-select-option :value="0">原始状态</a-select-option>
              <a-select-option :value="1">小单位</a-select-option>
              <a-select-option :value="2">中单位</a-select-option>
              <a-select-option :value="3">大单位</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetData">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFromCollapse v-model="expand" />
          </a-button-group>
        </a-col>
        <template v-if="expand">
          <a-col :span="4">
            <a-form-item label="分类" class="smart-margin-bottom0">
              <CateSelect v-model:value="formData.cate_id" :multiple="true" placeholder="分类" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="商品名称" class="smart-margin-bottom0">
              <a-input v-model:value.trim="formData.goods_name" placeholder="商品名称、助记码" allowClear />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="收款方式" class="smart-margin-bottom0">
              <EnumSelect enum-name="RECEIVE_TYPE_ENUM" v-model:value="formData.payment_type" :multiple="true" placeholder="收款方式" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="签收状态" class="smart-margin-bottom0">
              <EnumSelect enum-name="LIMIT_STATRS_ENUM" v-model:value="formData.sign_status" :multiple="true" placeholder="签收状态" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="品牌" class="smart-margin-bottom0">
              <Select name="Brand" v-model:value="formData.brand_id" :multiple="true" placeholder="品牌" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="业务员" class="smart-margin-bottom0">
              <Select name="Salesman" v-model:value="formData.salesman_id" :multiple="true" placeholder="业务员" @input-enter="onSearch" />
            </a-form-item>
          </a-col>
        </template>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="onExport" type="primary" v-privilege="'statistics:sales:report'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ fixed: true, selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, column, record }">
          <template v-if="column.dataIndex === 'order_no'">
            <CopyText :text="text">
              <text @click="toSaleOrder(record)">{{ text }}</text>
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'goods_name'">
            <CopyText :text="text">
              {{ text }}
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'type'">
            <a-tag :color="TagColor[record.type]">{{ getDescByValue('GOODS_TYPE_ENUM', Number(record.type)) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'num'"> {{ text }}{{ record.unit_name }} </template>
          <template v-if="column.dataIndex === 'received_number'"> {{ text }}{{ record.unit_name }} </template>
          <template v-if="column.dataIndex === 'is_self'">
            <a-tag :color="Number(text) === 1 ? 'success' : 'error'">{{ Number(text) === 1 ? '自提' : '统配' }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'delivery_status'">
            <a-tag :color="TagColor[record.delivery_status]">{{ getDescByValue('SMART_SIGN_ENUM', Number(record.delivery_status)) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'payment_type'">
            <a-tag :color="TagColor[record.payment_type]">{{ getDescByValue('RECEIVE_TYPE_ENUM', Number(record.payment_type)) }}</a-tag>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <a-table-summary-cell />
              <a-table-summary-cell>总计</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ totalData.num }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ totalData.total_price }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ totalData.received_number }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ totalData.received_money }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="() => `共${total}条`" />
    </div>
  </a-card>
</template>
<script setup lang="ts">
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import { outApi } from '@/api/business/report/warehouse-api'
import CateSelect from '@/components/business/select/cate-select.vue'
import TableOperator from '@/components/support/table-operator/index.vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useResize } from '@/hooks/web/use-resize-hook'
import Select from '@/components/business/select/index.vue'
import SearchFromCollapse from '@/components/support/search-form-collapse/index.vue'
import eventEmitter from '@/lib/event-emitter'
import customEventName from '@/views/business/report/warehouse/intelligent-sales/intelligent-event'
import { useEnums } from '@/hooks/plugins/useEnums'
const { getDescByValue } = useEnums()
// ----------------------------- tag状态 -----------------------------
enum TagColor {
  'error' = 0,
  'success',
  'processing',
  'warning',
  'default'
}
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()
//总计
const totalData = ref({
  num: '',
  received_money: '',
  received_number: '',
  total_price: ''
})
// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '订单编号',
    dataIndex: 'order_no'
  },
  {
    title: '门店名称',
    dataIndex: 'store_name'
  },
  {
    title: '商品名称',
    dataIndex: 'goods_name'
  },
  {
    title: '单位',
    dataIndex: 'unit_name'
  },
  {
    title: '品牌',
    dataIndex: 'brand_name'
  },
  {
    title: '分类',
    dataIndex: 'cate_name',
    width: 80
  },
  {
    title: '销售类型',
    dataIndex: 'type'
  },
  {
    title: '订单商品数量',
    dataIndex: 'num'
  },
  {
    title: '下单单价',
    dataIndex: 'real_price'
  },
  {
    title: '订单商品金额',
    dataIndex: 'total_price'
  },
  {
    title: '签收商品数量',
    dataIndex: 'received_number'
  },
  {
    title: '签收商品金额',
    dataIndex: 'received_money'
  },
  {
    title: '配送方式',
    dataIndex: 'is_self'
  },
  {
    title: '签收状态',
    dataIndex: 'delivery_status'
  },
  {
    title: '签收时间',
    dataIndex: 'sign_time'
  },
  {
    title: '结算方式',
    dataIndex: 'payment_type'
  },
  {
    title: '出库仓库',
    dataIndex: 'warehouse_name'
  },
  {
    title: '出库时间',
    dataIndex: 'load_time'
  },
  {
    title: '业务员',
    dataIndex: 'salesman_name'
  },
  {
    title: '配送司机',
    dataIndex: 'driver_name'
  },
  {
    title: '协送员',
    dataIndex: 'escort_driver_name'
  },
  {
    title: '整单备注',
    dataIndex: 'order_remark'
  },
  {
    title: '明细备注',
    dataIndex: 'goods_remark'
  },
  {
    title: '开单时间',
    dataIndex: 'create_time'
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const formData = ref({
  create_time: DEFAULT_TIME_RANGE.value,
  goods_name: '',
  time_type: 1,
  unit_type: 0,
  salesman_id: [],
  store_id: [],
  payment_type: undefined,
  sign_status: [],
  brand_id: [],
  cate_id: []
})
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData } = useQuery({
  fetchDataApi: async (params) => {
    const data = {
      ...params,
      order_type: 'refund',
      create_time: formData.value.create_time?.filter(Boolean).join(','),
      goods_name: formData.value.goods_name,
      salesman_id: formData.value.salesman_id.join(','),
      store_id: formData.value.store_id.join(','),
      payment_type: formData.value.payment_type,
      sign_status: formData.value.sign_status.join(','),
      brand_id: formData.value.brand_id.join(','),
      cate_id: formData.value.cate_id.join(','),
      time_type: formData.value.time_type,
      unit_type: formData.value.unit_type
    }
    const res = await outApi.querySmartSaleList(data)
    totalData.value = res.data.sum_data
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {},
  queryFormOp: {}
})
onMounted(() => {
  queryData()
})
eventEmitter.on(customEventName.QueryList, ({ dealer_id }) => {
  // formData.value.dealer_id = dealer_id
  queryData()
})
// 跳转至退货单
const router = useRouter()
function toSaleOrder(record) {
  if (record.sale_type == 1 && record.order_type == 2) {
    router.push(`/sale/return?no=${record.order_no}`)
  } else if (record.sale_type == 2 && record.order_type == 2) {
    router.push(`/sales/order?no=${record.order_no}`)
  }
}
// ---------------------------- 批量 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([])

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys
}

// 搜索重置
const resetData = () => {
  formData.value.goods_name = ''
  formData.value.time_type = 1
  formData.value.unit_type = 0
  formData.value.create_time = DEFAULT_TIME_RANGE.value
  formData.value.salesman_id = []
  formData.value.store_id = []
  formData.value.payment_type = undefined
  formData.value.sign_status = []
  formData.value.brand_id = []
  formData.value.cate_id = []
  eventEmitter.emit(customEventName.RefreshDealerList)
  eventEmitter.emit(customEventName.QueryDealerList, {
    page: 1
  })
  queryData()
}
// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const data = {
    create_time: formData.value.create_time?.filter(Boolean).join(','),
    goods_name: formData.value.goods_name,
    salesman_id: formData.value.salesman_id.join(','),
    store_id: formData.value.store_id.join(','),
    payment_type: formData.value.payment_type,
    sign_status: formData.value.sign_status.join(','),
    brand_id: formData.value.brand_id.join(','),
    cate_id: formData.value.cate_id.join(','),
    time_type: formData.value.time_type,
    unit_type: formData.value.unit_type,
    export: '1',
    order_type: 'refund',
    ids: selectedRowKeyList.value.join(',')
  }
  outApi.exportSmartSale(data)
}
</script>
